package com.lh.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 异步请求
 */
@Slf4j
public class AsyncRequest {
    /**
     * 外接口总数
     */
    private static final int INTERFACE_COUNT = 100;
    /**
     * 调用接口的线程池
     */
    private static ExecutorService executorService = new ThreadPoolExecutor(INTERFACE_COUNT, INTERFACE_COUNT * 3, 10L,
            TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());


    private List<CyclicBarrier> barriers = new ArrayList<>();
    private List<Future<?>> futures = new ArrayList<>();

    public static ExecutorService getExecutorService(){
        return executorService;
    }

    public void submit(Callable<?> future) {
        AsyncRequestCallableProxy proxy = new AsyncRequestCallableProxy(future);
        Future<?> submit = executorService.submit(future);
        futures.add(submit);
    }

    public void git() {
        for (Future<?> future : futures) {
            try {
                Object o = future.get();
            } catch (InterruptedException e) {
                log.error("errorInfo:{}",e);
            } catch (ExecutionException e) {
                log.error("errorInfo:{}",e);
            }
        }
    }
}
